<template>
  <div :id="chartsData.id" :style="{ width: '100%', height: '300px', backgroundColor: '#fff' }"></div>
</template>
<script>
import echarts from 'echarts'
let echartData = {}
export default {
  data() {
    return {}
  },
  props: ['chartsData'],
  watch: {
    chartsData: {
      // 正确给 cData 赋值的 方法
      deep: true,
      handler(newVal, oldVal) {
        echartData = newVal
      },
    },
  },
  mounted() {
    echartData = this.chartsData
    var unit = this.chartsData.unit
    var colors = ['#3AA1FF', '#F2637B', '#4ECB73', '#FA973E']
    var newColor = []
    for (var i = 0; i < echartData.legendData.length; i++) {
      newColor.push(colors[i])
    }
    var myChart = echarts.init(document.getElementById(echartData.id))
    const option = {
      color: newColor,
      legend: {
        data: echartData.legendData,
        show: true,
        top: '0',
        bottom: 0,
        left: 'center',
        icon: 'circle', // 设置前面图形为圆形
        textStyle: {
          color: '#333',
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let tip = params[0].name + '<br>'
          for (let i = 0; i < params.length; i++) {
            tip += params[i].marker + params[i].seriesName + ': ' + params[i].value + unit + '<br>'
          }
          return tip
        },
      },
      grid: {
        top: '40px',
        left: '3%',
        right: '3%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: echartData.xData,
        axisLabel: {
          fontSize: 10,
        },
      },
      yAxis: {
        type: 'value',
        // max: unit === ' %' ? 100 : '',
        max: function (value) {
          if (unit.trim() === '%') {
            return 100
          } else {
            // return value()
            // return myChart.getModel().getComponent('yAxis', idx).axis.scale._extent[1]
            // console.log('------', myChart.getModel().getComponent('yAxis').axis.scale._extent)
            return Math.ceil(myChart.getModel().getComponent('yAxis').axis.scale._extent[1])
          }
        },
        min: 0,
        // splitNumber: unit === ' %' ? 11 : '',
        axisLabel: {
          formatter: '{value}' + unit, //  刻度标签的内容格式器，支持字符串模板和回调函数两种形式，按照自己需求设置
        },
        splitLine: {
          // 网格线
          lineStyle: {
            type: 'dashed', // 设置网格线类型 dotted：虚线   solid:实线
          },
          show: true, // 隐藏或显示
        },
      },
      series: echartData.seriesDate,
    }
    myChart.setOption(option)
    window.addEventListener('resize', function () {
      //   让我们图表调用resize方法
      myChart.resize()
    })
  },
}
</script>
